package cn.mastor.system.controller;

import cn.mastor.basic.anno.PreAuthorize;
import cn.mastor.pet.domain.Pet;
import cn.mastor.system.domain.Menu;
import cn.mastor.system.service.IRoleService;
import cn.mastor.system.domain.Role;
import cn.mastor.system.query.RoleQuery;
import cn.mastor.basic.util.AjaxResult;
import cn.mastor.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    public IRoleService roleService;


    /**
     * 保存和修改公用的
     * @param role  传递的实体
     * @return AjaxResult转换结果
     */
    /**
    * 删除对象信息
    * @param
    * @return
    */
    @PutMapping
    @PreAuthorize(name = "保存角色",sn = "role:save")
    public AjaxResult addOrUpdate(@RequestBody Role employee){
        System.out.println(employee);
        if (null == employee.getId()){
            roleService.add(employee);
        }else {
            roleService.update(employee);
        }
        return AjaxResult.me().success();
    }
    @DeleteMapping(value="/{id}")
    @PreAuthorize(name = "删除角色",sn = "role:delete")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            roleService.delete(id);
        } catch (Exception e) {
        e.printStackTrace();

        }
        return AjaxResult.me().success();
    }

    //获取用户
    @GetMapping("/{id}")
    public Role get(@PathVariable("id")Long id)
    {
        return roleService.findById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Role> list(){

        return roleService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    @PreAuthorize(name = "列表角色",sn = "role:list")
    public PageList<Role> json(@RequestBody RoleQuery query)
    {
        PageList<Role> pageList = roleService.queryByPage(query);
        List<Role> rows = pageList.getRows();
        for (int i = 0; i < rows.size(); i++) {
            List<Long> list = roleService.findByroId(rows.get(i).getId());
            List<Long> list1 = roleService.findBypeId(rows.get(i).getId());
            List<Menu> menus = roleService.findmenuAll(rows.get(i).getId());
//            System.out.println("这是"+role);
            rows.get(i).setMenus(list);
            rows.get(i).setPermissions(list1);
            rows.get(i).setOwnMenus(menus);
        }
        System.out.println(pageList);
        return pageList;
    }
}
